package com.quanyan.pay.api.chinaums.service.impl;

import com.quanyan.common.utils.ExcelUtils;
import com.quanyan.common.utils.FtpUtils;
import com.quanyan.common.utils.GsonUtils;
import com.quanyan.common.utils.TimeUtils;
import com.quanyan.pay.api.chinaums.service.ChinaumsAPIService;
import com.quanyan.pay.api.chinaums.vo.UmBillDataItem;
import com.quanyan.pay.api.chinaums.vo.UmBillDataRespVo;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

/**
 * Created by Zheng.Ke
 * Date 2017/4/5.
 */
@Service("chinaumsAPIService")
public class ChinaumsAPIServiceImpl implements ChinaumsAPIService {

    // 默认端口21
    private static final int defaultPort = 21;
    // 根目录
    private static final String defaultPathName = "/";

    @Override
    public List<String> getXlsFileNameList(String hostName, String userName, String password) {
        List<String> fileNames = FtpUtils.getFileNameList(hostName, defaultPort, userName, password, defaultPathName);

        for (Iterator<String> iterator = fileNames.iterator(); iterator.hasNext(); ) {
            String fileName = iterator.next();
            if (!fileName.endsWith("xls") && !fileName.endsWith("xlsx")) { // 非xls xlsx格式的排除
                iterator.remove();
            }
        }
        return fileNames;
    }

    @Override
    public UmBillDataRespVo processBillData(String hostName, String userName, String password, String xlsFileName) {
        // 创建临时文件
        File billXlsFile = null;
        try {
            billXlsFile = File.createTempFile("Chinaums_", xlsFileName.substring(xlsFileName.lastIndexOf(".")));
        } catch (IOException e) {
            e.printStackTrace();
        }

        boolean isDownload = FtpUtils.downloadFile(hostName, defaultPort, userName, password, defaultPathName, xlsFileName, billXlsFile);
        if (!isDownload) {
            throw new RuntimeException("无法下载文件，可能原因：1、文件名不正确；2、下载过程中出错");
        }

        UmBillDataRespVo respVo = this. processBillData(billXlsFile);
        // 删除临时文件
        billXlsFile.deleteOnExit();
        return respVo;
    }

    @Override
    public UmBillDataRespVo processBillData(File billXlsFile) {
        List<String[]> data = ExcelUtils.readToList(billXlsFile);
        List<UmBillDataItem> billData = new ArrayList<>();
        // 表头
        int startRowNum = 3;
        for (int i=startRowNum; i<data.size(); i++) {
            if (data.get(i)[0].contains("交易总笔数")) { // 表尾
                break;
            }
            // 数据域
            UmBillDataItem umBillDataItem = processXlsDataArray(data.get(i));
            billData.add(umBillDataItem);
        }

        UmBillDataRespVo respVo = new UmBillDataRespVo();
        respVo.setBillData(billData);
        return respVo;
    }

    private UmBillDataItem processXlsDataArray(String[] xlsDataArray) {
        UmBillDataItem umBillDataItem = new UmBillDataItem();
        for (int i=0; i<xlsDataArray.length; i++) {
            String currentStr = xlsDataArray[i];
            switch (i) {
                case 0: // 商户号
                    umBillDataItem.setMchId(currentStr);
                    break;
                case 1: // do nothing
                    break;
                case 2: // 交易时间 11:02:27
                    String previousStr = xlsDataArray[i-1]; // Sat Oct 08 00:00:00 CST 2016
                    String tradeTimeStr = previousStr + " " + currentStr; // Sat Oct 08 00:00:00 CST 2016 11:02:27
                    Date tradeTime = TimeUtils.engStringToDate(tradeTimeStr, "EEE MMM dd 00:00:00 z yyyy hh:mm:ss");
                    umBillDataItem.setTradeTime(tradeTime);
                    break;
                case 3: // 终端号
                    umBillDataItem.setTerminalId(currentStr);
                    break;
                case 4: // 交易类型
                    umBillDataItem.setTradeType(currentStr);
                    break;
                case 5: // 卡号
                    umBillDataItem.setCardNo(currentStr);
                    break;
                case 6: // 交易金额
                    umBillDataItem.setTradeFee(new BigDecimal(currentStr));
                    break;
                case 7: // 清算金额
                    umBillDataItem.setClearFee(new BigDecimal(currentStr));
                    break;
                case 8: // 手续费
                    umBillDataItem.setHandlingFee(new BigDecimal(currentStr));
                    break;
                case 9: // 流水号
                    umBillDataItem.setTransactionId(currentStr);
                    break;
                case 10: // 系统跟踪号
                    umBillDataItem.setSysTraceNo(currentStr);
                    break;
                case 11: // 卡类型
                    umBillDataItem.setCardType(currentStr);
                    break;
                case 12: // 交易参考号
                    umBillDataItem.setReferenceNo(currentStr);
                    break;
                case 13: // 发卡行
                    umBillDataItem.setBank(currentStr);
                    break;
            }
        }
        return umBillDataItem;
    }
}
